using System;
using System.Collections.Generic;
using AI;
using AI.FSM;
using UnityEngine;
using XNode;

namespace AI.FSM.Builder
{
    public class FSMStateGraph : NodeGraph ,IBehaviourBuilder<FSMRunState>
    {
        public IBehaviour<TAgent,FSMRunState> Build<TAgent> ()
        {
            var nextIndex = 0;
            var states = new List<FSMState<TAgent>>();
            var nodeIdToStateIndexMap = new Dictionary<int,int>();
            enterState.Build(ref nextIndex,states,nodeIdToStateIndexMap);

            #if UNITY_EDITOR
                nodeIdToIndexMap = nodeIdToStateIndexMap;
            #endif
            return new FSM<TAgent>(states.ToArray());
        }

        public override Node AddNode(Type type)
        {
            //只允许正确类型的节点
            if(typeof(FSMStateGraphNode).IsAssignableFrom(type) == false &&
                typeof(FSMTransitionGraphNode).IsAssignableFrom(type) == false)
            {
                return null;
            }

            //默认第一个节点为root
            var node = base.AddNode(type);
            var stateNode = node as FSMStateGraphNode;
            if(stateNode != null && enterState == null)
            {
                SetEnterNode(stateNode);
            }

            return node;
        }

        internal FSMStateGraphNode EnterState => enterState;
        internal void SetEnterNode(FSMStateGraphNode node)
        {
            if(enterState != null)
            {
                enterState.IsEnter = false;
            }
        }

        [SerializeField]
        FSMStateGraphNode enterState;

        #if UNITY_EDITOR

        Dictionary<int,int> nodeIdToIndexMap = new Dictionary<int, int>();

        #endif
    } 
}
